package 康复训练_JavaGo并驾齐驱;

import 链表.ListNode;

public class Jz06从尾到头打印链表 {

    /**
     * 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
     */

    private int count;

    public int[] reversePrint(ListNode head) {

        // 翻转一次, 再翻转一次
        head = reverseList(head);
        int[] result = new int[count];

        ListNode node = head;
        int index = 0;
        while (node != null) {
            result[index++] = node.val;
            node = node.next;
        }

        reverseList(head);

        return result;
    }

    private ListNode reverseList(ListNode head) {
        // A -> B -> C
        ListNode last = null;
        ListNode next = null;
        ListNode node = head;
        while (node != null) {
            count++;
            next = node.next;
            node.next = last;
            last = node;
            node = next;
        }

        return last;
    }

}
